# -*- coding: utf-8 -*-
"""
Tag-Network Plugin for Pelican - by rainy
====================================

This plugin provide required data of tags
(and their connections defined by co-occurrence in the same article)
that can be rendered by springy(https://github.com/dhotson/springy)
"""
from pelican import signals

Network = {"nodes":[], "links":[]}
AC = 1
def Node(ID = 0, Name = 'None', Value = 0, Url = 'Url'):
  return {'ID': ID, 'Name': Name, 'Value': Value, 'Url': Url}
def Link(Src = 0, Tar = 0, Value = 0):
  return {'Src': Src, 'Tar': Tar, 'Value': Value}
def addNode(name, url):
  global AC
  i = 0
  for node in Network['nodes']:
    if(node['Name'] == name):
      Network['nodes'][i]['Value'] += 1
      return node['ID']
    i += 1
  Network['nodes'].append(Node(AC, name, 1, url))
  AC += 1
  return AC - 1

def insertLink(n1, n2):
  global Network
  i = 0
  for link in Network['links']:
    if((n1[0] == link['Src'] and n2[0] == link['Tar']) or (n2[0] == link['Src'] and n1[0] == link['Tar'])):
      Network['links'][i]['Value'] += 1
      return
    i += 1
  Network['links'].append(Link(n1[0], n2[0], 1))
      
def addLink(tags):
  if(len(tags) < 2):
    return
  for i in range(len(tags) - 1):
    for j in range(i+1, len(tags)):
      #print "Insert : (%s, %s)" % (tags[i][0], tags[j][0])
      insertLink(tags[i], tags[j])

def tagsnet(generator):
  global Network
  for article in generator.articles:
    artTags = []
    for tag in article.tags:
      tid = addNode(tag.name, tag.url)
      artTags.append([tid, tag.name])
    #print artTags
    addLink(artTags)

  generator.context['tags_network'] = Network 
def register():
  signals.article_generator_finalized.connect(tagsnet)

